package member

import (
	"gpt-api/framework/codes"
	"gpt-api/framework/ginplus"
	"gpt-api/pkg/model"
	"gpt-api/pkg/response"
	"gpt-api/pkg/util"

	"github.com/gin-gonic/gin"
)

// 获取成员事件详情
func (h *Handler) GetEvent(c *gin.Context) error {
	// 验证参数
	userId := ginplus.GetUserID(c)
	var req struct {
		Id uint `form:"id" binding:"required,gte=0"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 查询信息
	event, err := (&model.Events{}).GetEventById(h.db, req.Id)
	if err != nil {
		return ginplus.ReplyError(c, codes.MemberEventNotFound, err)
	}
	if event.UserID != uint(userId) {
		return ginplus.ReplyError(c, codes.MemberEventNotFound, err)
	}

	// 响应数据
	eventInfo := &response.EventInfoResp{
		Id:          event.ID,
		MemberId:    uint64(event.MemberID),
		Title:       event.Title,
		Content:     event.Content,
		UpdataTime:  event.UpdatedAt.Format("2006-01-02 15:04:05"),
		CreateTime:  event.CreatedAt.Format("2006-01-02 15:04:05"),
		EventTypeID: event.EventTypeID,
		StartTime:   event.StartTime.Format("2006-01-02 15:04:05"),
		EndTime:     event.EndTime.Format("2006-01-02 15:04:05"),
		Location:    event.Location,
		EventImages: []response.EventImageResp{},
	}
	// 遍历图片
	for _, image := range event.EventImages {
		eventInfo.EventImages = append(eventInfo.EventImages, response.EventImageResp{
			ImageUrl: image.ImageUrl,
			MemberId: uint64(image.MemberID),
		})
	}

	return ginplus.ReplyJSON(c, eventInfo)
}

// 获取成员事件列表
func (h *Handler) GetEventsList(c *gin.Context) error {
	// 验证参数
	userId := ginplus.GetUserID(c)
	var req struct {
		MemberID uint `form:"member_id" binding:"required,gt=0"`
		Page     int  `form:"page" default:"1"`
		Size     int  `form:"size" default:"10"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 查询成员事件列表
	events, err := (&model.Events{}).GetEventsByUserIdAndMemberId(h.db, userId, uint64(req.MemberID), req.Page, req.Size)
	if err != nil {
		return ginplus.ReplyError(c, codes.MemberEventNotFound, err)
	}

	// 遍历数据
	var resp []*response.EventListResp
	for _, event := range events {
		// 整理数据
		resp = append(resp, &response.EventListResp{
			Id:        event.ID,
			Title:     event.Title,
			Content:   event.Content,
			StartTime: event.StartTime.Format("2006-01-02 15:04:05"),
			EndTime:   event.EndTime.Format("2006-01-02 15:04:05"),
			EventType: response.EventTypeResp{
				Id:   event.EventType.ID,
				Name: event.EventType.Name,
			},
			EventImage: []response.EventImageResp{},
		})

		// 整理图片
		for _, image := range event.EventImages {
			resp[len(resp)-1].EventImage = append(resp[len(resp)-1].EventImage, response.EventImageResp{
				ImageUrl: image.ImageUrl,
				MemberId: uint64(image.MemberID),
			})
		}
	}
	return ginplus.ReplyJSON(c, resp)
}

// 添加成员事件
func (h *Handler) AddEvent(c *gin.Context) error {
	// 验证参数
	userId := ginplus.GetUserID(c)
	var req struct {
		MemberId    uint     `json:"member_id" binding:"required,gt=0"`
		EventTypeID int      `json:"event_type_id" binding:"required,gt=0"`
		Title       string   `json:"title"`
		Content     string   `json:"content"`
		StartTime   string   `json:"start_time" binding:"required"`
		EndTime     string   `json:"end_time"`
		Location    string   `json:"location"`
		Id          uint     `json:"id" binding:"gte=0"`
		Images      []string `json:"event_images"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 判断图片最多9张
	if len(req.Images) > 9 {
		return ginplus.ReplyError(c, codes.ImagesMaxLimitTo9, nil)
	}

	// 判断事件类型
	eventType, err := model.EventType{}.GetEventType(h.db, uint(req.EventTypeID))
	if err != nil {
		return ginplus.ReplyError(c, codes.EventTypeNotFound, err)
	}
	if eventType.UserID != uint(userId) && eventType.UserID != 0 {
		return ginplus.ReplyError(c, codes.EventTypeNotFound, err)
	}

	// 整理数据
	event := &model.Events{
		UserID:      uint(userId),
		MemberID:    req.MemberId,
		EventTypeID: req.EventTypeID,
		Title:       req.Title,
		Content:     req.Content,
		Location:    req.Location,
	}
	// 开始日期
	if req.StartTime != "" {
		start_time := util.TimestampToTime(util.StrToTimestamp(req.StartTime))
		event.StartTime = &start_time
	}
	// 结束日期
	if req.EndTime != "" {
		end_time := util.TimestampToTime(util.StrToTimestamp(req.EndTime))
		event.EndTime = &end_time
	}
	// 如果传入ID，则更新
	if req.Id > 0 {
		// 查询旧数据
		oldEvent, _ := event.GetEventById(h.db, uint(req.Id))
		if oldEvent.UserID != uint(userId) {
			return ginplus.ReplyError(c, codes.MemberEventNotFound, err)
		}

		// 更新事件
		event.ID = uint64(req.Id)
		event.MemberID = oldEvent.MemberID
	}

	// 更新OR新增
	if err := event.AddOrUpdateEvent(h.db, *event, req.Images); err != nil {
		return ginplus.ReplyInternalError(c, err)
	}
	return ginplus.ReplyJSON(c, nil)
}

// 删除成员事件
func (h *Handler) DeleteEvent(c *gin.Context) error {
	// 验证参数
	userId := ginplus.GetUserID(c)
	var req struct {
		Id uint `form:"id" binding:"required,gte=0"`
	}
	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 查询事件信息
	event, err := (&model.Events{}).GetEventById(h.db, req.Id)
	if err != nil {
		return ginplus.ReplyError(c, codes.MemberEventNotFound, err)
	}

	// 删除事件
	if err := event.DeleteEventByEventTypeIdAndUserId(h.db, req.Id, uint(userId)); err != nil {
		return ginplus.ReplyError(c, codes.MemberEventNotFound, err)
	}
	return ginplus.ReplyJSON(c, nil)
}
